package com.agileai.pm.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.jasig.cas.client.authentication.AttributePrincipal;

import com.agileai.hotweb.common.HttpRequestHelper;
import com.agileai.hotweb.domain.core.Profile;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.filter.HotwebUserCacher;
import com.agileai.pm.cxmodule.ProjectInfoManage;
import com.agileai.pm.domain.Consts;
import com.agileai.pm.domain.Project;

public class HotwebUserCasFilter extends com.agileai.hotweb.filter.HotwebUserCasFilter{
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
	    HttpServletRequest httpRequest = (HttpServletRequest) request;
	    AttributePrincipal attributePrincipal =  (AttributePrincipal)httpRequest.getUserPrincipal();
	    if (attributePrincipal != null) {
	        String loginName = attributePrincipal.getName();
	        Profile profile = getProfile(httpRequest);
	        if (profile == null) {
	        	String fromIpAddress = HttpRequestHelper.getRemoteHost(httpRequest);
				String appName = httpRequest.getContextPath().substring(1);
				HotwebUserCacher userCacher = HotwebUserCacher.getInstance(appName);
				User user = userCacher.getUser(loginName);
				
				profile = new Profile(loginName,fromIpAddress,user);
				HttpSession session = httpRequest.getSession(true);
				session.setAttribute(appName + "." + Profile.PROFILE_KEY, profile);
				
				if (user.hasRole(Consts.ProjectMasterRole) || user.isAdmin()){
					String userPk = user.getUserId();
					ProjectInfoManage projectInfoManage = (ProjectInfoManage)this.lookupService("projectInfoManageService");
					List<Project> projectList = projectInfoManage.queryProjectList(userPk);
					if (projectList != null && projectList.size() > 0){
						Project project = projectList.get(0);
						this.getSessionAttributes(httpRequest).put(Consts.ProjectSessionKey, project);
					}else{
						Project project = Project.createEmptyProject();
						this.getSessionAttributes(httpRequest).put(Consts.ProjectSessionKey, project);
					}
				}else{
					String userPk = user.getUserId();
					ProjectInfoManage projectInfoManage = (ProjectInfoManage)this.lookupService("projectInfoManageService");
					List<Project> projectList = projectInfoManage.queryProjectList(userPk);
					if (projectList != null && projectList.size() > 0){
						Project project = projectList.get(0);
						this.getSessionAttributes(httpRequest).put(Consts.ProjectSessionKey, project);
					}
				}				
	        }
	    }
	    chain.doFilter(request, response);		
	}

}
